package cn.lblbc.album

import android.app.RecoverableSecurityException
import android.content.ContentResolver
import android.content.ContentUris
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.PopupMenu
import androidx.core.content.FileProvider
import androidx.viewpager2.widget.ViewPager2
import cn.lblbc.album.adapter.ImageViewerAdapter
import cn.lblbc.album.model.ImageItem
import java.io.File

class ImageViewerActivity : AppCompatActivity() {
    
    companion object {
        const val EXTRA_IMAGE_LIST = "extra_image_list"
        const val EXTRA_CURRENT_POSITION = "extra_current_position"
        private const val REQUEST_DELETE_PERMISSION = 1001
    }
    
    private lateinit var viewPager: ViewPager2
    private lateinit var imageItems: List<ImageItem>
    private var currentPosition: Int = 0
    private var pendingDeleteImageItem: ImageItem? = null
    private var pendingDeletePosition: Int = -1
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_viewer)
        
        // 隐藏状态栏
        hideSystemUI()
        
        // 获取传递的数据
        imageItems = intent.getSerializableExtra(EXTRA_IMAGE_LIST) as List<ImageItem>
        currentPosition = intent.getIntExtra(EXTRA_CURRENT_POSITION, 0)
        
        initViews()
    }
    
    private fun initViews() {
        viewPager = findViewById(R.id.viewPager)
        
        val adapter = ImageViewerAdapter(imageItems)
        viewPager.adapter = adapter
        viewPager.currentItem = currentPosition
        
        // 设置页面变化监听器
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                currentPosition = position
            }
        })
        
        // 设置返回按钮
        findViewById<ImageView>(R.id.backButton).setOnClickListener {
            finish()
        }
        
        // 设置更多按钮
        findViewById<ImageView>(R.id.moreButton).setOnClickListener {
            showPopupMenu()
        }
    }
    
    private fun showPopupMenu() {
        val moreButton = findViewById<View>(R.id.moreButton)
        val popupMenu = PopupMenu(this, moreButton, Gravity.END)
        popupMenu.menuInflater.inflate(R.menu.menu_image_viewer, popupMenu.menu)
        
        popupMenu.setOnMenuItemClickListener { menuItem ->
            val imageItem = imageItems[currentPosition]
            when (menuItem.itemId) {
                R.id.action_delete -> {
                    deleteImage(imageItem, currentPosition)
                    true
                }
                R.id.action_share -> {
                    shareImage(imageItem)
                    true
                }
                else -> false
            }
        }
        
        popupMenu.show()
    }
    
    private fun deleteImage(imageItem: ImageItem, position: Int) {
        try {
            // 首先尝试使用 MediaStore API 删除（推荐方式）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Android 10 及以上版本使用 MediaStore API
                deleteImageWithMediaStore(imageItem, position)
            } else {
                // Android 10 以下版本使用传统文件删除方式
                deleteImageWithFile(imageItem, position)
            }
        } catch (e: SecurityException) {
            // 处理权限异常
            handleSecurityException(e, imageItem, position)
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "删除失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun handleSecurityException(e: Exception, imageItem: ImageItem, position: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && e is RecoverableSecurityException) {
            // 保存删除信息，以便在权限请求后继续操作
            pendingDeleteImageItem = imageItem
            pendingDeletePosition = position
            
            // 请求权限
            try {
                startIntentSenderForResult(
                    e.userAction.actionIntent.intentSender,
                    REQUEST_DELETE_PERMISSION,
                    null,
                    0,
                    0,
                    0,
                    null
                )
            } catch (sendEx: Exception) {
                sendEx.printStackTrace()
                Toast.makeText(this, "无法请求删除权限", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(this, "没有删除权限", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun deleteImageWithMediaStore(imageItem: ImageItem, position: Int) {
        try {
            val contentResolver: ContentResolver = contentResolver
            val uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageItem.id)
            
            val rowsDeleted = contentResolver.delete(uri, null, null)
            if (rowsDeleted > 0) {
                // 从列表中移除已删除的图片
                val updatedList = imageItems.toMutableList()
                updatedList.removeAt(position)
                imageItems = updatedList
                
                // 更新适配器
                viewPager.adapter?.notifyItemRemoved(position)
                
                Toast.makeText(this, "图片已删除", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show()
            }
        } catch (e: SecurityException) {
            // 将安全异常重新抛出，由调用者处理
            throw e
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "删除失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun deleteImageWithFile(imageItem: ImageItem, position: Int) {
        val file = File(imageItem.path)
        if (file.exists()) {
            if (file.delete()) {
                // 同时从媒体库中移除
                val contentResolver: ContentResolver = contentResolver
                val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                val selection = "${MediaStore.Images.Media.DATA}=?"
                val selectionArgs = arrayOf(imageItem.path)
                contentResolver.delete(uri, selection, selectionArgs)
                
                // 从列表中移除已删除的图片
                val updatedList = imageItems.toMutableList()
                updatedList.removeAt(position)
                imageItems = updatedList
                
                // 更新适配器
                viewPager.adapter?.notifyItemRemoved(position)
                
                Toast.makeText(this, "图片已删除", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        
        if (requestCode == REQUEST_DELETE_PERMISSION) {
            if (resultCode == RESULT_OK && pendingDeleteImageItem != null && pendingDeletePosition != -1) {
                // 用户授予了删除权限，继续删除操作
                val imageItem = pendingDeleteImageItem!!
                val position = pendingDeletePosition
                
                // 重置pending变量
                pendingDeleteImageItem = null
                pendingDeletePosition = -1
                
                // 执行删除操作
                try {
                    deleteImageWithMediaStore(imageItem, position)
                } catch (e: Exception) {
                    e.printStackTrace()
                    Toast.makeText(this, "删除失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            } else {
                Toast.makeText(this, "删除权限被拒绝", Toast.LENGTH_SHORT).show()
                // 重置pending变量
                pendingDeleteImageItem = null
                pendingDeletePosition = -1
            }
        }
    }
    
    private fun shareImage(imageItem: ImageItem) {
        val file = File(imageItem.path)
        if (file.exists()) {
            try {
                val uri = FileProvider.getUriForFile(
                    this,
                    "${packageName}.fileprovider",
                    file
                )
                
                val shareIntent = Intent().apply {
                    action = Intent.ACTION_SEND
                    putExtra(Intent.EXTRA_STREAM, uri)
                    type = "image/*"
                    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                }
                startActivity(Intent.createChooser(shareIntent, "分享图片"))
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(this, "分享失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        } else {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun hideSystemUI() {
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )
    }
    
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        // 全屏模式下触摸屏幕边缘恢复系统UI
        if (event?.action == MotionEvent.ACTION_DOWN) {
            toggleSystemUI()
            return true
        }
        return super.onTouchEvent(event)
    }
    
    private fun toggleSystemUI() {
        if (window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_FULLSCREEN == 0) {
            hideSystemUI()
        } else {
            showSystemUI()
        }
    }
    
    private fun showSystemUI() {
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                )
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 恢复系统UI
        showSystemUI()
    }
}